package db

import (
	"log"
	"os"
	"time"

	"catering_sys_api/core/conf"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

// Init init DB
func InitGorm(c conf.Gorm) {
	var err error
	mysqlConfig := mysql.Config{
		DSN:                       c.Datasource,
		SkipInitializeWithVersion: false, // 根据版本自动配置
	}
	_default := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             200 * time.Millisecond, // 慢 SQL 阈值
			LogLevel:                  logger.Error,           // 日志级别
			IgnoreRecordNotFoundError: true,                   // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,                  // 禁用彩色打印
		},
	)
	_default.LogMode(logger.Info)

	DB, err = gorm.Open(mysql.New(mysqlConfig), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		Logger:                                   _default,
	})

	if err != nil {
		panic(err)
	}

	sqlDB, _ := DB.DB()
	sqlDB.SetMaxIdleConns(c.MaxIdleConns)
	sqlDB.SetMaxOpenConns(c.MaxOpenConns)
}
